package com.bxait.toymail.member.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.bxait.com.exception.MemberSocialUserEnum;
import com.bxait.com.utils.HttpUtils;
import com.bxait.com.utils.PageUtils;
import com.bxait.com.utils.Query;
import com.bxait.com.vo.member.*;
import com.bxait.toymail.member.dao.MemberLevelDao;
import com.bxait.toymail.member.entity.MemberLevelEntity;
import com.bxait.toymail.member.exception.PhoneExistException;
import com.bxait.toymail.member.exception.UsernameExistException;
import org.apache.http.HttpResponse;
import org.apache.http.util.EntityUtils;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import com.bxait.toymail.member.dao.MemberDao;
import com.bxait.toymail.member.entity.MemberEntity;
import com.bxait.toymail.member.service.MemberService;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;


@Service("memberService")
public class MemberServiceImpl extends ServiceImpl<MemberDao, MemberEntity> implements MemberService {


    @Resource
    MemberLevelDao memberLevelDao;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<MemberEntity> page = this.page(
                new Query<MemberEntity>().getPage(params),
                new QueryWrapper<MemberEntity>()
        );

        return new PageUtils(page);
    }

    /*
     * @param vo
     * @==============History===============<br/>
     * @Description //   用户登录的验证信息
     * @Date 2023/4/21 2023/4/21
     * @Author < a href="2277411582@qq.com">chen</ a>
     * @return
     */
    @Override
    public MemberEntity login(UserLoginVo vo) {
        // 账号
        String account = vo.getAccount();
        // 明文密码
        String password = vo.getPassword();

        // 1.根据账号,查出用户。

        // SELECT * FROM `ums_member` WHERE username=? OR mobile=?
        MemberDao memberDao = this.baseMapper;
        MemberEntity entity = memberDao.selectOne(new QueryWrapper<MemberEntity>().eq("username", account)
                .or().eq("mobile", account));
        // 登录失败,直接返回空
        if(entity == null){
            return null;
        }
        // 密文密码
        String passwordDB = entity.getPassword();
        BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
        boolean matches = passwordEncoder.matches(password, passwordDB);
        // 密码比对成功,返回真实用户信息;对比失败,返回空
        if(matches){
            return entity;
        }else {
            return null;
        }

    }

    /*
     * @param vo
     * @==============History===============<br/>
     * @Description //   处理用户注册的请求
     * @Date 2023/4/21 2023/4/21 
     * @Author < a href="2277411582@qq.com">chen</ a>
     * @return void
     */
    @Transactional
    @Override
    public void register(UserRegisterVo vo) {
        // 走到这一步,用户需要注册的用户信息都是校验好的;直接校验库里面有没有重复的手机号和用户名
        MemberEntity memberEntity = new MemberEntity();
        memberEntity.setSourceType(MemberSocialUserEnum.TOY_MAIL_REG_USER.getCode());
        // 查询用户默认等级
        MemberLevelEntity levelEntity = memberLevelDao.getDefaultLevel();
        memberEntity.setLevelId(levelEntity.getId());

        // 校验手机号,用户名是否唯一;失败返回异常
        checkPhoneUnique(vo.getPhone());
        checkUsernameUnique(vo.getUserName());

        memberEntity.setMobile(vo.getPhone());
        memberEntity.setUsername(vo.getUserName());
        memberEntity.setNickname(vo.getUserName());

        memberEntity.setCreateTime(new Date());

        // 加密
        BCryptPasswordEncoder bCryptPasswordEncoder = new BCryptPasswordEncoder();
        String encode = bCryptPasswordEncoder.encode(vo.getPassword());

        memberEntity.setPassword(encode);

        this.save(memberEntity);
    }

    /*
     * @param socialUser
     * @==============History===============<br/>
     * @Description //   社交用户登录注册二合一
     * @Date 2023/4/21 2023/4/21
     * @Author < a href="2277411582@qq.com">chen</ a>
     * @return
     */
    @Transactional
    @Override
    public MemberEntity oauthLogin(SocialUser socialUser) {
        Integer sourceType = socialUser.getSourceType();
        MemberDao memberDao = this.baseMapper;
        // 微博用户
        if(sourceType == MemberSocialUserEnum.WEIBO_LONGIN_USER.getCode()){
            WeiBoSocialUser boSocialUser = socialUser.getBoSocialUser();
            // 根据社交账号id获取这个用户在不在我们的库里
            String uid = boSocialUser.getUid();
            // 库里面有这个社交用户,查出来直接返回
            QueryWrapper<MemberEntity> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("social_uid",uid).eq("source_type",MemberSocialUserEnum.WEIBO_LONGIN_USER.getCode());
            MemberEntity memberEntityByWeiBo = memberDao.selectOne(queryWrapper);
            if(memberEntityByWeiBo != null){
                // 更新这个社交用户
                MemberEntity updateByWeiBo = new MemberEntity();
                updateByWeiBo.setId(memberEntityByWeiBo.getId());
                updateByWeiBo.setAccessToken(boSocialUser.getAccess_token());
                updateByWeiBo.setExpiresIn(String.valueOf(boSocialUser.getExpires_in()));
                memberDao.updateById(updateByWeiBo);
                memberEntityByWeiBo.setAccessToken(boSocialUser.getAccess_token());
                memberEntityByWeiBo.setExpiresIn(String.valueOf(boSocialUser.getExpires_in()));
               return memberEntityByWeiBo;
            }else {
                // 注册微博社交用户
                MemberEntity insetMemberByWeiBo = new MemberEntity();
                try{
                    //3、查询当前社交用户的社交账号信息（昵称，性别等）
                    Map<String,String> query = new HashMap<>();
                    query.put("access_token",boSocialUser.getAccess_token());
                    query.put("uid",boSocialUser.getUid());
                    HttpResponse response = HttpUtils.doGet("https://api.weibo.com", "/2/users/show.json", "get", new HashMap<String, String>(), query);
                    if(response.getStatusLine().getStatusCode() == 200){
                        //查询成功
                        String json = EntityUtils.toString(response.getEntity());
                        JSONObject jsonObject = JSON.parseObject(json);
                        //昵称
                        String name = jsonObject.getString("name");
                        String gender = jsonObject.getString("gender");
                        insetMemberByWeiBo.setNickname(name);
                        insetMemberByWeiBo.setGender("m".equals(gender)?1:0);
                    }
                }catch (Exception e){}
                MemberLevelEntity levelEntity = memberLevelDao.getDefaultLevel();
                insetMemberByWeiBo.setLevelId(levelEntity.getId());
                insetMemberByWeiBo.setSocialUid(boSocialUser.getUid());
                insetMemberByWeiBo.setUsername(boSocialUser.getIsRealName());
                insetMemberByWeiBo.setAccessToken(boSocialUser.getAccess_token());
                insetMemberByWeiBo.setPassword(encryption("123456"));
                insetMemberByWeiBo.setExpiresIn(String.valueOf(boSocialUser.getExpires_in()));
                insetMemberByWeiBo.setMobile("123456789");
                memberDao.insert(insetMemberByWeiBo);
                return insetMemberByWeiBo;
            }

        }
        // 微信用户
        if(sourceType == MemberSocialUserEnum.WEI_XIN_LONGIN_USER.getCode()){
            WeiXinSocialUser xinSocialUser = socialUser.getXinSocialUser();
            // 根据社交账号id获取这个用户在不在我们的库里
            String uid = xinSocialUser.getOpenid();
            // 库里面有这个社交用户,查出来直接返回
            QueryWrapper<MemberEntity> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("social_uid",uid).eq("source_type",MemberSocialUserEnum.WEI_XIN_LONGIN_USER.getCode());
            MemberEntity memberEntityByWeiXi = memberDao.selectOne(queryWrapper);
            if(memberEntityByWeiXi != null){
                // 更新这个用户
                MemberEntity updateByWeiXi = new MemberEntity();
                updateByWeiXi.setId(memberEntityByWeiXi.getId());
                updateByWeiXi.setAccessToken(xinSocialUser.getAccess_token());
                memberDao.updateById(updateByWeiXi);
                memberEntityByWeiXi.setAccessToken(xinSocialUser.getAccess_token());
                return memberEntityByWeiXi;
            }else {
                // 注册这个用户
                MemberEntity insetMemberByWeiXi = new MemberEntity();
                insetMemberByWeiXi.setNickname(xinSocialUser.getNickName());
                insetMemberByWeiXi.setUsername(xinSocialUser.getNickName());
                insetMemberByWeiXi.setHeader(xinSocialUser.getImg());
                insetMemberByWeiXi.setCreateTime(new Date());
                insetMemberByWeiXi.setAccessToken(xinSocialUser.getAccess_token());
                insetMemberByWeiXi.setSourceType(MemberSocialUserEnum.WEI_XIN_LONGIN_USER.getCode());
                MemberLevelEntity levelEntity = memberLevelDao.getDefaultLevel();
                insetMemberByWeiXi.setLevelId(levelEntity.getId());
                insetMemberByWeiXi.setSocialUid(uid);
                insetMemberByWeiXi.setPassword(encryption("123456"));
                insetMemberByWeiXi.setMobile("123456789");
                memberDao.insert(insetMemberByWeiXi);
                return insetMemberByWeiXi;
            }
        }
        return null;
    }

    /*
     * @param userName
     * @==============History===============<br/>
     * @Description //   校验用户名是否唯一
     * @Date 2023/4/21 2023/4/21
     * @Author < a href="2277411582@qq.com">chen</ a>
     * @return void
     */
    private void checkUsernameUnique(String userName) throws UsernameExistException{
        MemberDao memberDao = this.baseMapper;
        Integer count = memberDao.selectCount(new QueryWrapper<MemberEntity>().eq("username", userName));
        if (count > 0) {
            throw new UsernameExistException();
        }
    }

    /*
     * @param phone
     * @==============History===============<br/>
     * @Description //   校验手机号是否唯一
     * @Date 2023/4/21 2023/4/21
     * @Author < a href="2277411582@qq.com">chen</ a>
     * @return void
     */
    private void checkPhoneUnique(String phone) throws PhoneExistException{
        MemberDao memberDao = this.baseMapper;
        Integer mobile = memberDao.selectCount(new QueryWrapper<MemberEntity>().eq("mobile", phone));
        if(mobile > 0){
            throw new PhoneExistException();
        }
    }


    /*
     * @param code
     * @==============History===============<br/>
     * @Description //   密码加密的方法
     * @Date 2023/5/13 2023/5/13
     * @Author < a href="2277411582@qq.com">chen</ a>
     * @return java.lang.String
     */
    private String encryption(String code){
        BCryptPasswordEncoder bCryptPasswordEncoder = new BCryptPasswordEncoder();
        String encode = bCryptPasswordEncoder.encode(code);
        return encode;
    }

}